package ecs.net.systems;

import ecs.core.BaseSystem;
import ecs.core.Entity;
import ecs.net.EventType;
import ecs.net.Status;
import ecs.net.components.AddressComponent;
import ecs.net.components.ServerSocketComponent;
import ecs.net.components.SocketComponent;
import ecs.net.components.StatusComponent;

import java.io.IOException;
import java.net.Socket;

public class SocketInitSystem extends BaseSystem {

    public SocketInitSystem()
    {
        super();
        interestingComponentTypes(new Class[]{AddressComponent.class, SocketComponent.class
                , StatusComponent.class});
    }

    public void init()
    {
        entityComponents().forEach(components -> {
            AddressComponent address = (AddressComponent) components.get(0);
            SocketComponent socket = (SocketComponent) components.get(1);
            StatusComponent status = (StatusComponent) components.get(2);
            try {
                socket.socket(new Socket(address.host(), address.port()));
                status.status(Status.Connected);
            } catch (IOException e) {

            }
        });
    }

    @Override
    public void handle(EventType event, Object param) {
        super.handle(event, param);
        if(event == EventType.SocketCreate)
        {
            Socket socket = (Socket) param;
            SocketComponent soc = new SocketComponent();
            soc.socket(socket);
            StatusComponent status = new StatusComponent();
            status.status(Status.Connected);
            Entity entity = new Entity();
            entity.add(soc);
            entity.add(status);
            parent().in(entity);
        }
    }
}
